package study.springboot.redis.support.jedis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

@Slf4j
@Configuration
public class JedisCfg {

    @Bean
    @ConfigurationProperties(prefix = "jedis.user")
    public JedisProperties jedisProp() {
        return new JedisProperties();
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisProperties jedisProp) {
        //（★）basic config
        RedisStandaloneConfiguration standaloneConfig = new RedisStandaloneConfiguration();
        //主机
        standaloneConfig.setHostName(jedisProp.getHost());
        //端口
        standaloneConfig.setPort(jedisProp.getPort());
        //数据库
        standaloneConfig.setDatabase(jedisProp.getDatabase());
        //密码
        standaloneConfig.setPassword(jedisProp.getPassword());

        //（★）pool config
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //最大连接数
        poolConfig.setMaxTotal(jedisProp.getMaxTotal());
        //最小空闲连接
        poolConfig.setMinIdle(jedisProp.getMinIdle());
        //最大空闲连接
        poolConfig.setMaxIdle(jedisProp.getMaxIdle());
        //最大阻塞等待时间
        poolConfig.setMaxWaitMillis(jedisProp.getMaxWait());
        //连接耗尽时是否阻塞, false报异常，true阻塞直到超时, 默认true
        poolConfig.setBlockWhenExhausted(jedisProp.isBlockWhenExhausted());

        //空闲连接检查间隔
//        poolConfig.setTimeBetweenEvictionRunsMillis();
//        //
//        poolConfig.setNumTestsPerEvictionRun();
//        //
//        poolConfig.setEvictorShutdownTimeoutMillis();
//        //
//        poolConfig.setMinEvictableIdleTimeMillis();

        //
        poolConfig.setTestOnCreate(jedisProp.isTestOnCreate());
        //调用borrowObject方法时，是否进行有效检查
        poolConfig.setTestOnBorrow(jedisProp.isTestOnBorrow());
        //调用returnObject方法时，是否进行有效检查
        poolConfig.setTestOnReturn(jedisProp.isTestOnReturn());
        //
        poolConfig.setTestWhileIdle(jedisProp.isTestWhileIdle());

        //（★）client config
        JedisClientConfiguration clientConfig = JedisClientConfiguration.builder()
                .clientName(jedisProp.getClientName())
                .usePooling()
                .poolConfig(poolConfig)
                .build();

        return new JedisConnectionFactory(standaloneConfig, clientConfig);
    }
}
